package com.itheima.controller.user;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.UserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = "体检")
@Transactional
public class UserOrderController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserOrderService userOrderService;

    /**
     * 根据预约id查询预约信息
     */
    @GetMapping("/findById")
    @ApiOperation("根据预约id查询预约信息")
    public Result findById(Integer id) {
        try {
            log.info("根据预约id查询预约信息");
            Order order = userOrderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, order);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 体检预约
     */
    @PostMapping("/submitOrder")
    @ApiOperation("体检预约")
    public Result submitOrder(@RequestBody Map map) throws Exception {
        //从redis中获取保存的验证码
        String telephone = (String) map.get("telephone");//获取手机号
        String validateCodeRedis = (String) redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);//获取验证码
        //截取redis中存储的验证码 保留后四位
        if (validateCodeRedis != null) {
            validateCodeRedis = validateCodeRedis.substring(validateCodeRedis.length() - 4);
        }

        String validateCode = (String) map.get("validateCode");
        //验证码进行比对
        if (validateCodeRedis != null && validateCodeRedis.equals(validateCode) && validateCode != null) {
            //成功则调用service方法完成预约
            map.put("orderType", Order.ORDERTYPE_WEIXIN); //设置预约类型 微信预约 电话预约
            Result result = userOrderService.order(map);
            return result;
        } else {
            //不成功返回错误信息
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }


}
